package edu.caece.automaton;

import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class AbstractTransition implements Transition{
	protected String triggerExpr;
	protected Pattern triggerExprPattern;
	protected State sourceState;
	protected State destinationState;
	protected static final Log LOGGER = LogFactory.getLog(AbstractTransition.class);
	
	public AbstractTransition (State sourceState, State destinationState, String triggerExpr){
		this.sourceState = sourceState;
		this.destinationState = destinationState;
		this.triggerExpr = triggerExpr;
		this.triggerExprPattern = Pattern.compile(this.triggerExpr);
	}
	
	public String getTriggerExpression() {
		return this.triggerExpr;
	}

	public State getDestinationState() {
 		return this.destinationState;
	}

	public State getSourceState() {
		return this.sourceState;
	}
	
	@Override
	public boolean equals(Object obj) {
		boolean isEquals = false;
		
		if (obj instanceof Transition){
			Transition other = (Transition) obj;
			isEquals = (this.sourceState.equals(other.getSourceState()));
			isEquals = isEquals && (this.destinationState.equals(other.getDestinationState()));
			isEquals = isEquals && (this.triggerExpr.equals(other.getTriggerExpression()));
		}
		return isEquals;
	}

	@Override
	public int hashCode() {
		String hashString;
		
		hashString = this.triggerExpr.toString() + this.sourceState.toString() + this.destinationState.toString();
		return hashString.hashCode() ;
	}
	
	@Override
	public String toString() {
		return this.sourceState.toString() + " |-- " + this.triggerExpr + " --> " + this.destinationState.toString();
	}

	public boolean matches(Character character) {
		boolean match = this.triggerExprPattern.matcher(character.toString()).matches();
		if (match)
			LOGGER.debug("Match:OK  Character: " + character + " Expression:" + this.triggerExpr);
		return match;
	}
}
